/**
 * ClickQuiz
 * (c) Bayerischer Rundfunk www.br.de
 * Author: Vladimir Mikulicic
 * http://yui.github.io/yuicompressor/
 */

;
(function ($, window, document, undefined) {

    // Create the defaults once
    var pluginName = "ClickQuiz";

    // The actual plugin constructor
    function Plugin(element, options) {
        this.element = element;
        this.index = -1;
        this.images;
        this.clicks = 0;
        this.json;
        this.settings = $.extend({}, options);
        this._name = pluginName;
        this.init();
    }

    Plugin.prototype = {
        init: function () {
            var _self = this;
            _self.createGameStructure();
            _self.loadData();
            $(_self.element).find('div.CQstartScreen').click(function (event) {
                event.preventDefault();
                var parent = $(this).context.parentNode;
                $("div.CQstartScreen").remove();
                _self.setQuestions(_self);
                $(_self.element).css('cursor', 'pointer').find('#CQboard').live('click',{_self: _self}, _self.removeTile);
                BR.Tracking.track(_self.settings.comscoreTag,'start','0','view',undefined);
            });
        },
        makeBoard: function () {
            this.createTiles();
            if (this.index > -1) {
                $(this.element).find("#CQboard").die()
                $(this.element).find("#CQboard").live('click',{_self: this}, this.removeTile);
            }
            (this.index < this.images.length - 1) ? this.index++ : this.index = 0;
            $(this.element).find('#CQboard').css({'background-image': 'url(' + this.images[this.index].url + ')'});
        },
        createTiles: function () {
            $(this.element).find('#CQtiles').empty();
            for (var i = 1; i <= 20; i++) {
                if (i % 2 == 0) {
                    $(this.element).find('#CQtiles').append('<div class="CQtile">' +
                        '<div class="CQsegment CQrotate90"></div>' +
                        '<div class="CQsegment CQrotate-90"></div></div>');
                } else {
                    if (i == 5) {
                        $(this.element).find('#CQtiles').append('<div class="CQtile">' +
                            '<div class="CQsegment CQrotate0"></div>' +
                            '<div class="CQklicksegment"></div></div>');
                    } else {
                        $(this.element).find('#CQtiles').append('<div class="CQtile">' +
                            '<div class="CQsegment CQrotate0"></div>' +
                            '<div class="CQsegment CQrotate180"></div></div>');
                    }
                }
            }
            this.tileDeck = $(this.element).find('div.CQtile > div.CQsegment');
        },
        removeTile: function (event) {
            var _self = event.data._self;
            _self.removeRandomTile(_self);
            _self.clicks++;
        },
        removeRandomTile: function (_self) {
            var tileDeck = _self.tileDeck;
            if (tileDeck != undefined) {
                var i = Math.floor(Math.random() * tileDeck.length);
                $(tileDeck[i]).remove();
                tileDeck.splice(i, 1)[0];
                if (tileDeck.length < 1) {
                    $(_self.element).find('#QCboard').die("click");
                    _self.setStar();
                    $(".CQresult-bg a").click(function (event) {
                        event.preventDefault();
                        $(".CQresult-bg").remove();
                        _self.makeBoard();
                        _self.setQuestions(_self);
                        _self.clicks = 0;
                        BR.Tracking.track(_self.settings.comscoreTag,'start',_self.index,'view',undefined);
                    });
                }
            }
        },
        removeAllTiles: function (_self) {
            for (var i = _self.tileDeck.length; i > 0; i--) {
                _self.removeRandomTile(_self);
            }
        },
        setQuestions: function (_self) {
            var answerNum;
            var correctBox;
            var options = _self.shuffle(_self.images[_self.index].options);
            var boxes = $(_self.element).find('ul > li');
            var correct;
            boxes.find('a').removeAttr('style');
            boxes.find('div').remove();

            for (var i = 0; i < options.length; i++) {
                if (options[i].correct > 0) {
                    correctBox = boxes[i];
                    correct = options[i];
                    answerNum = $(correctBox).find('span').text();
                }
                $(boxes[i]).unbind().append('<div>' + options[i].name + '</div>');
                $(boxes[i]).find('a').live('click',{o: options[i]}, function (event) {
                    event.preventDefault();
                    $(correctBox).find('a').css("background-image", "url(/schnipsel-static/nachrichten/wahl/html-kandidaten-raten/img/button_wahl_orange.png)");
                    if (event.data.o.correct == '1') {
                        _self.result = {c: 'gruen', a: _self.calculateClicks(), n: 'Richtig!<br/> Die Antwort ist ' + answerNum + '.'};
                        BR.Tracking.track(_self.settings.comscoreTag,'geraten_richtig',_self.clicks,'view',undefined);
                    } else {
                        _self.result = {c: 'rot', a: _self.calculateClicks(), n: 'Falsch!<br/> Die Antwort ist ' + answerNum + '.'};
                        BR.Tracking.track(_self.settings.comscoreTag,'geraten_falsch',_self.clicks,'view',undefined);
                    }
                    boxes.click(function() { return false; });
                    _self.removeAllTiles(_self);
                })
            };
        },
        setStar: function () {
            //FIXME: Pad in CSS-Klasse auslagern
            $(this.element).find('#CQboard').append('<div class="CQresult-bg">' +
                '<div class="CQstern" style="background-image:url(/schnipsel-static/nachrichten/wahl/html-kandidaten-raten/img/stern-' + this.result.c + '' + this.result.a + '.png)"></div>' +
                '<div class="CQanswer">' + this.result.n + '</div>' +
                '<a href="#" class="CQgoBtn CQresult"></a>' +
                '</div>');
        },
        calculateClicks: function () {
            if (this.clicks < 1)
                return  "-0";
            else if (this.clicks < 6)
                return "-1";
            else if (this.clicks < 14)
                return "-2";
            else if (this.clicks < 37)
                return "-3";
            else
                return "-4";
        },
        loadData: function () {
            var _self = this;
            $.ajax({
                dataType: 'json',
                type: 'GET',
                cache: false,
                url: _self.settings.dataUrl,
                error: function (obj, msg, e) {

                },
                success: function (json) {
                    _self.images = _self.shuffle(json.quizdata.images);
                    _self.makeBoard();
                    _self.createInfo(json.quizdata.info);
                }
            });
        },
        shuffle: function (arr) {
            for (var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
            return arr;
        },
        createGameStructure: function () {
            $(this.element).append('<div id="CQboard">' +
                '<div id="CQtiles"></div>' +
                '<div class="CQstartScreen"><a href="#" class="CQgoBtn CQstart"></a></div></div>' +
                '<div id="CQquestions">' +
                '<div class="CQheader"></div><div><ul>' +
                '<li><a href="#"><span>A</span></a></li>' +
                '<li><a href="#"><span>B</span></a></li>' +
                '<li><a href="#"><span>C</span></a></li>' +
                '</ul></div></div>');
        },
        createInfo: function (info) {
            $(this.element).append('<div id="CQinfo">' +
                '<div class="CQinfoContent">' + info + '</div>' +
                '<div class="CQinfoBtn"></div>' +
                '</div>');
            $('#CQinfo').mouseover(function (event) {
                $("#CQinfo").stop(true, false).animate({left: "+1px"}, 500);
            });
            $('#CQinfo').mouseout(function (event) {
                $("#CQinfo").stop(true, false).animate({left: "-160px"}, 500);
            });
        }
    };

    $.fn[ pluginName ] = function (options) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Plugin(this, options));
            }
        });
    };

})(jQuery, window, document);